<?php

namespace app\common\model\shop;

use app\common\model\BaseModel;
use think\Exception;

/**
 * 门店导购积分流水
 * Class ShopSalesmanPoint
 * @package app\common\model\shop
 */
class ShopSalesmanPointModel extends BaseModel
{
    //
    protected $name = 'shop_salesman_point';

    // 设置字段信息
    protected $schema = [
        'id' => 'int',        //
        'mer_id' => 'string',        // 所属商户
        'shop_id' => 'int',        // 所属店铺
        'salesman_id' => 'int',        // 所属导购
        'point' => 'int',        // 变动积分
        're_point' => 'int',        // 变动后积分
        'vp_id' => 'int',        // 关联活动
        'create_at' => 'datetime',        // 创建时间
    ];

    /**
     * 导购调整积分
     * @param int $user_id
     * @param string $mer_id
     * @param $point
     * 类型 1：增加 2减少
     * @throws Exception
     */
    public function saveMemberPoint(int $user_id, string $mer_id , $point ,$type = 1, $memo= ''): void
    {

        try {
            $info = $this->db('shop_salesman')->where('mer_id', $mer_id)->where('id', $user_id)
                ->find();
            if (empty($info)) {
                throw  new Exception('导购不存在或已删除',API_ERROR);
            }
            $this->db()->startTrans();
            $re_point = $info['point'] + $point;
            if ($type == 2) {
                $re_point = $info['point'] - $point;
                if ($re_point < 0) {
                    throw  new Exception('积分不足',API_ERROR);
                }
            }

            $this->db('shop_salesman')->where('mer_id', $mer_id)->where('id', $user_id)
                ->update(['point' => $re_point]);
            $this->db()->insert([
                'mer_id' => $mer_id,
                'salesman_id' => $user_id,
                'point' => $point,
                're_point' => $re_point,
                'memo' => $memo,
                'type' => $type,
                'shop_id' => $info['shop_id'],
            ]);
            $this->db()->commit();
        } catch (Exception $e) {
            $this->db()->rollback();
            throw $e;
        }
    }
}
